import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';

class CountryCodesWidget extends StatefulWidget {
  final String currentSelectCode;
  final ValueChanged<String> selectCallBack;

  CountryCodesWidget({Key key, this.currentSelectCode, this.selectCallBack})
      : super(key: key);

  @override
  _CountryCodesWidgetState createState() => _CountryCodesWidgetState();
}

class _CountryCodesWidgetState extends State<CountryCodesWidget> {
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();
  Map<String, dynamic> data = {
    'Popular': {
      "Singapore": "+65",
      "Malaysia": "+60",
      "China": "+86",
      "India": "+91"
    },
    "A": {
      "Afghanistan": "+93",
      'Albania': '+355',
      'Algeria': '+357',
      'American Samoa': '++213',
      'Andorra': '+353',
      'Albaniaa': '+354',
      'Albanisad': '+356',
    }
  };
  String _currentSelectCode;

  @override
  void initState() {
    super.initState();
    Map<String, dynamic> _data = {};
    final countryCodes =
        Config.settingApp.countryCode.where((e) => e.isFavorite == 1).toList();
    Map<String, String> popular = {};
    for (final item in countryCodes) {
      popular[item.name] = item.countryCode;
    }
    _data['Popular'] = popular;
    final copyList = List.of(Config.settingApp.countryCode);
    copyList.sort((a, b) => a.group.compareTo(b.group));
    for (final item in copyList) {
      if (_data.containsKey(item.group)) {
        Map groupMap = _data[item.group];
        groupMap[item.name] = item.countryCode;
      } else {
        _data[item.group] = {
          item.name: item.countryCode,
        };
      }
    }
    data = _data;
    _currentSelectCode = widget.currentSelectCode;
    _searchController.addListener(_handleSearchInput);
  }

  void _handleSearchInput() {
    setState(() {});
  }

  bool _onSearchInputGroup(MapEntry<String, dynamic> element) {
    String searchInput = _searchController.text;
    return element.value
        .toString()
        .contains(RegExpUtils.getSearchRegExp(searchInput));
  }

  dynamic _onSearchInputItem(Map<String, String> element) {
    String searchInput = _searchController.text;

    Map<String, String> data = {};
    for (final item in element.entries) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.key)) {
        data[item.key] = item.value;
      }
    }
    return data;
  }

  @override
  void dispose() {
    super.dispose();
    _searchController.dispose();
    _searchFocusNode.dispose();
  }

  void onChangeSelectCode(String value) {
    if (value != _currentSelectCode) {
      setState(() {
        _currentSelectCode = value;
      });
      widget.selectCallBack?.call(_currentSelectCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height * 0.50;
    List<Widget> slivers;
    if (_searchController.text.isNotEmpty) {
      slivers = data.entries
          .toList()
          .where(_onSearchInputGroup)
          .map((e) => buildSliver(e.key, _onSearchInputItem(e.value)))
          .toList();
    } else {
      slivers = data.entries
          .toList()
          .map((e) => buildSliver(e.key, e.value))
          .toList();
    }
    return Container(
      height: height,
      child: Column(
        children: [
          SizedBox(
            height: getDp(17),
          ),
          SearchInputField(
            key: ValueKey('Search Input'),
            controller: _searchController,
            focusNode: _searchFocusNode,
          ),
          SizedBox(
            height: getDp(17),
          ),
          Expanded(
              child: CupertinoScrollbar(
            child: CustomScrollView(
              slivers: slivers,
            ),
          )),
        ],
      ),
    );
  }

  Widget buildSliver(String title, Map<String, String> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.entries.length,
          ),
        ),
      );

  Widget buildSliverItem(Map<String, String> data, int i) {
    bool isSelect = _currentSelectCode == data.entries.toList()[i].value;
    return PressedOpacityButton(
      onPressed: () => onChangeSelectCode(data.entries.toList()[i].value),
      padding: EdgeInsets.symmetric(
        horizontal: getDp(30),
        vertical: getDp(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          NormalRadio(
            isSelect: isSelect,
            title: data.entries.toList()[i].key,
          ),
          Text(
            data.entries.toList()[i].value,
            style: TextStyle(
              color: aceBlackColor,
              fontSize: getSp(16),
              fontWeight: isSelect ? FontWeight.w700 : FontWeight.w400,
              height: 1,
            ),
          ),
        ],
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
